package com.jzo2o.customer.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.IdUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationAuditService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务人员认证审核表 服务实现类
 * </p>
 *
 * @author szc
 * @since 2025-09-17
 */
@Service
public class WorkerCertificationAuditServiceImpl extends ServiceImpl<WorkerCertificationAuditMapper, WorkerCertificationAudit> implements IWorkerCertificationAuditService {

    @Resource
    private IWorkerCertificationService workerCertificationService;

    /**
     * 服务人员认证
     *
     * @param workerCertificationAuditAddReqDTO 服务人员认证信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void certification(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        WorkerCertification workerCertification = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertification.class);
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        workerCertification.setId(currentUser.getId());
        workerCertification.setCertificationTime(LocalDateTime.now());
        // 判断是否已提交过认证信息
        LambdaQueryWrapper<WorkerCertification> queryWrapper = Wrappers.<WorkerCertification>lambdaQuery()
                .eq(WorkerCertification::getId, currentUser.getId());
        WorkerCertification workerCertificationServiceDb = workerCertificationService.getOne(queryWrapper);
        if (ObjectUtils.isNull(workerCertificationServiceDb)) {
            //插入服务人员认证信息表
            workerCertificationService.save(workerCertification);
        }else if (workerCertificationServiceDb.getCertificationStatus().equals(CertificationStatusEnum.FAIL.getStatus())){
            //更新服务人员认证信息表
            workerCertification.setUpdateTime(LocalDateTime.now());
            workerCertification.setId(workerCertificationServiceDb.getId());
            workerCertificationService.updateById(workerCertification);
        }
        //插入服务人员认证审核表
        WorkerCertificationAudit bean = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertificationAudit.class);
        bean.setId(IdUtils.getSnowflakeNextId());
        bean.setServeProviderId(currentUser.getId());
        save(bean);
    }

    /**
     * 查询最新驳回原因
     *
     * @return 驳回原因
     */
    @Override
    public RejectReasonResDTO getRejectReason() {
        CurrentUser currentUser = UserContext.getCurrentUser();
        String result = lambdaQuery().eq(WorkerCertificationAudit::getServeProviderId, currentUser.getId())
                .eq(WorkerCertificationAudit::getAuditStatus, 1)
                .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                .eq(WorkerCertificationAudit::getAuditStatus, 1)
                .orderByDesc(WorkerCertificationAudit::getCreateTime)
                .last("limit 1")
                .select(WorkerCertificationAudit::getRejectReason)
                .oneOpt()
                .map(WorkerCertificationAudit::getRejectReason)
                .orElse("");
        return new RejectReasonResDTO(result);
    }

    @Override
    public PageResult<WorkerCertificationAuditResDTO> pageQuery(WorkerCertificationAuditPageQueryReqDTO workerCertificationAuditPageQueryReqDTO) {
        return PageHelperUtils.selectPage(workerCertificationAuditPageQueryReqDTO, () ->
                baseMapper.queryList(workerCertificationAuditPageQueryReqDTO.getName(),
                        workerCertificationAuditPageQueryReqDTO.getIdCardNo(),
                        workerCertificationAuditPageQueryReqDTO.getAuditStatus(),
                        workerCertificationAuditPageQueryReqDTO.getCertificationStatus()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Integer certificationStatus, String rejectReason, Long id) {
        WorkerCertificationAudit workerCertificationAudit = getById(id);
        if (ObjectUtils.isNull(workerCertificationAudit)) {
            throw new ForbiddenOperationException("认证信息不存在");
        }
        Long serveProviderId = workerCertificationAudit.getServeProviderId();
        //更新服务人员认证信息表
        workerCertificationService.lambdaUpdate()
                .eq(WorkerCertification::getId, serveProviderId)
                .set(WorkerCertification::getCertificationStatus, certificationStatus)
                .set(WorkerCertification::getUpdateTime, LocalDateTime.now())
                .update();
        //更新服务人员认证审核表
        lambdaUpdate().eq(WorkerCertificationAudit::getId, id)
                .set(WorkerCertificationAudit::getAuditStatus, 1)
                .set(WorkerCertificationAudit::getAuditTime, LocalDateTime.now())
                .set(WorkerCertificationAudit::getCertificationStatus, certificationStatus)
                .set(StringUtils.isNotBlank(rejectReason), WorkerCertificationAudit::getRejectReason, rejectReason)
                .set(WorkerCertificationAudit::getAuditorId, UserContext.getCurrentUser().getId())
                .set(WorkerCertificationAudit::getAuditorName, UserContext.getCurrentUser().getName())
                .set(WorkerCertificationAudit::getUpdateTime, LocalDateTime.now())
                .update();
    }
}
